/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.spakehelpdesk.session;

import com.spakehelpdesk.entity.News;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.jms.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.joda.time.DateTime;

/**
 *
 * @author leehoanh
 */
@Stateless
@LocalBean
public class NewsSession {

    @Resource(mappedName = "jms/Notification/Queue")
    private Queue notificationQueue;
    @Resource(mappedName = "jms/Notification/QueueFactory")
    private ConnectionFactory notificationQueueFactory;
    @PersistenceContext(unitName = "Spake_Helpdesk-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    //select all News
    public List<News> getAll() {
        Query query = em.createNamedQuery("News.findAll");
        try {
            return query.getResultList();
        } catch (Exception e) {
            return null;
        }

    }
    //select all News sort by type
    public List<News> getAllSortByType() {
        Query query = em.createNamedQuery("News.sortByType");
        try {
            return query.getResultList();
        } catch (Exception e) {
            return null;
        }

    }
    //select all News sort by date create news
    public List<News> getAllSortByDate() {
        Query query = em.createNamedQuery("News.sortByDateGenerate");
        try {
            return query.getResultList();
        } catch (Exception e) {
            return null;
        }

    }
    //select all News have date create between date1 and date2
    public List<News> getNewsHaveDateBetween(Date date1,Date date2 ) {
        Query query = em.createNamedQuery("News.findByDateGenerateBetween");
        query.setParameter("dateGenerate1", date1);
        query.setParameter("dateGenerate2", date2);
        try {
            return query.getResultList();
        } catch (Exception e) {
            return null;
        }

    }
    //select all News have more reader that like
    public List<News> getNewsByRate(Double rate) {
        Query query = em.createNamedQuery("News.findByRate");
        query.setParameter("rate", rate);
        try {
            return query.getResultList();
        } catch (Exception e) {
            return null;
        }

    }
    //select news by type
    public List<News> getNewsByType(int idType) {
        Query query = em.createNamedQuery("News.findByType");
        query.setParameter("newTypeID", idType);
        try {
            return query.getResultList();
        } catch (Exception e) {
            return null;
        }
    }
    //select news by news's id

    public News getNewsById(int id) {
        Query query = em.createNamedQuery("News.findByNewID");
        query.setParameter("newID", id);
        try {
            return (News) query.getResultList();
        } catch (Exception e) {
            return null;
        }
    }
    //Update or edit a news

    public News updateNew(News news) {
        News updated = em.merge(news);
        try {
            sendJMSMessageToQueue(updated);//send task update to queue
        } catch (JMSException ex) {
            Logger.getLogger(AccountSession.class.getName()).log(Level.SEVERE, null, ex);
        }
        return updated;
    }
    //create a new News

    public void createNewNews(News news) {

        em.persist(news);//create

    }

    private Message createJMSMessageForjmsNotificationQueue(Session session, Object messageData) throws JMSException {
        // TODO create and populate message to send
        TextMessage tm = session.createTextMessage();
        tm.setText(messageData.toString());
        return tm;
    }

    private void sendJMSMessageToQueue(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = notificationQueueFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(notificationQueue);
            messageProducer.send(createJMSMessageForjmsNotificationQueue(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
